<template>
  <el-dialog title="批量处理数据" :visible.sync="showHandle" @close="cancelHandle" width="70%" append-to-body>
      <div class="handle-content">
        <!-- 业务操作 -->
        <el-card class="box-card" style="margin-bottom: 10px">
          <div slot="header">
            <span>业务操作</span>
          </div>
          <div>
<!--            <el-divider content-position="left">新版本</el-divider>-->
            <el-button type="primary" plain size="mini" @click="shenQdzdNew('dzd')">申请电子档</el-button>
            <el-button type="success" plain size="mini" @click="shenQdzdNew('zyzz')">申请纸质文件</el-button>
            <el-button type="warning" plain size="mini" @click="shenQdzdNew('dzdhzz')">申请电子和纸质</el-button>
<!--            <el-divider content-position="left">旧版本</el-divider>-->
<!--            <el-button type="primary" plain size="mini" @click="shenQdzd('dzd')">申请电子档</el-button>-->
<!--            <el-button type="success" plain size="mini" @click="shenQdzd('zyzz')">申请纸质文件</el-button>-->
<!--            <el-button type="warning" plain size="mini" @click="shenQdzd('dzdhzz')">申请电子和纸质</el-button>-->
<!--            <el-button plain size="mini" @click="clearWgdMb">清洗完工单模板</el-button>-->
          </div>
        </el-card>
        <!-- 批量更新选中数据 -->
        <el-card class="box-card" style="margin-bottom: 10px">
          <div slot="header">
            <span>批量更新选中数据</span>
<!--            <el-button style="float: right; padding: 1px 0" type="text">操作按钮</el-button>-->
          </div>
          <div>
            <el-form ref="bjdForm" label-position='left' :model="form" label-width="70px" size="mini">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="开票状态" prop="sfkp">
                    <el-radio-group v-model="form.sfkp">
                      <el-radio v-for="item in sfList" :label="item.dictValue" border>{{item.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="是否申请电子档" label-width="120px" prop="sfsqdzd">
                    <el-radio-group v-model="form.sfsqdzd">
                      <el-radio v-for="item in sfList" :label="item.dictValue" border>{{item.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="电子档是否给客户" prop="sfgkhdzd" label-width="130px">
                    <el-radio-group v-model="form.sfgkhdzd">
                      <el-radio v-for="item in sfList" :label="item.dictValue" border>{{item.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="打印状态" prop="zzdy">
                    <el-radio-group v-model="form.zzdy">
                      <el-radio v-for="item in sfList" :label="item.dictValue" border>{{item.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label="邮寄状态" prop="yyjkh">
                    <el-radio-group v-model="form.yyjkh">
                      <el-radio v-for="item in sfList" :label="item.dictValue" border>{{item.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="下场通知用户" prop="xctzyh" label-width="120px">
                    <el-radio-group v-model="form.xctzyh">
                      <el-radio v-for="item in sfList" :label="item.dictValue" border>{{item.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否回款" label-position='right' label-width="130px">
                    <el-radio-group v-model="form.sfhk" size="mini">
                      <el-radio border v-for="item in hkList" :label="item.dictValue">{{item.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
<!--                <el-form-item>-->
<!--                  <el-button :loading="buttonLoading" plain type="primary" @click="updateData">点击更新</el-button>-->
<!--                </el-form-item>-->
                <el-button :loading="buttonLoading" size="mini" plain type="primary" @click="updateData">点击更新</el-button>
              </el-row>
            </el-form>
          </div>
        </el-card>
        <!-- 完工单/报价单操作 -->
        <el-card class="box-card">
          <div slot="header">
            <span>完工单/报价单操作</span>
          </div>
          <div>
            <el-button type="primary" plain size="mini" @click="downExcelData">下载报价单</el-button>
            <el-button type="success" plain size="mini" @click="downExcelData_Wgd">下载完工单</el-button>
          </div>
        </el-card>
        <el-dialog title="生成电子档详情" :visible.sync="showDzdData" @close="cancelDzd" width="50%" append-to-body>
          <el-form ref="bjdForm" label-width="110px" size="mini">
            <el-row style="color: #F56C6C">
              <el-form-item label="预计回款时间数据为：当前的申请日期添加90天" label-width="500px"></el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="请选择申请日期" label-width="130px">
                <el-date-picker clearable
                                style="width: 100%"
                                v-model="sqrq"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择申请时间">
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item>
                <el-button :loading="buttonLoading" type="primary" @click="shenQdzd">点击生成</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-dialog>
      </div>
  </el-dialog>
</template>

<script>
import { downLoadZip } from '@/api/zipdownload'
import { batchUpdateZt, genDzd, genDzdNew } from '@/api/gd/ywdwgd'
export default {
  name: 'batchHandle',
  props: {
    showHandle: {
      type: Boolean
    },
    ids: {
      type: Array
    },
    ywdwgdList: {
      type: Array
    }
  },
  data() {
    return {
      buttonLoading: false,
      form: {
        sfkp: undefined,
        sfsqdzd: undefined,
        sfgkhdzd: undefined,
        zzdy: undefined,
        yyjkh: undefined
      },
      sfList: [],
      hkList: [],
      type: '',
      showDzdData: false,
      sqrq: ''
    }
  },
  created() {
    this.getDict()
  },
  methods: {
    showDzd(type) {
      let obj = this.parseTime(new Date(), '{y}-{m}-{d}')
      this.sqrq = obj
      this.type = type
      this.showDzdData = true
    },
    cancelDzd() {
      this.sqrq = ''
      this.showDzdData = false
    },
    // 申请电子档 旧
    shenQdzd(type) {
      const ids = this.ids;
      // 查询数据
      const data = this.ywdwgdList.filter(item => ids.some(id => id === item.id))
      // 判断要导出的数据是否有：证书份数，回款金额，回款时间
      const yws = []
      let obj = ""
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (item.wgdh === '' || item.wgdh === null) {  // 证书
          obj += "(客户为： " + item.khname + " 的数据待完善 完工单号 ),"
        }else if (item.zjfs === '' || item.zjfs === null) {  // 证书
          obj += "(完工编号为：" +item.wgdh + " 客户为： " + item.khname + " 的数据待完善 证书份数 ),"
        }else if (item.hkje === '' || item.hkje === null) {
          obj += "(完工编号为：" +item.wgdh + " 客户为： " + item.khname + " 的数据待完善 回款金额 ),"
        }else {
          yws.push(item)
        }
      }
      if (obj.length > 200) {
        obj = obj.substring(0, 200) + "..."
      }
      if (yws.length === 0) {
        this.$message.error('请先完善 ' + obj)
        return
      }
      let title = ""
      if (obj !== '') {
        title = '请确认 ' + obj+' 这些数据待完善，未完善的数据则不能生成电子档'
      }else {
        if (type === 'dzd') {
          title = '请确认是否要生成电子档'
        }else if (type === 'zyzz') {
          title = '请确认是否要生成纸质文件'
        }else {
          title = '请确认是否要生成纸质文件和电子档'
        }
      }
      this.$modal.confirm(title).then(() => {
        this.loading = true;
        let idList = yws.map(obj => obj.id)
        let param = {
          ids: idList.toString(),
          type: type
        }
        genDzd(param, 'blob').then(res => {
          this.showDzdData = false
          if (res !== null) {
            const binaryData = [];
            binaryData.push(res);
            let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
            const link = document.createElement('a');
            link.href = url
            let title = ""
            if (param.type === 'dzd') {
              title = "只申请电子档证书+"
              link.download = title + this.getTodayDate() + ".xls";
            }else if (param.type === 'zyzz') {
              title = "未回款先递证书申请+"
              link.download = title + this.getTodayDate() + ".docx";
            }else {
              title = "未回款先递证书申请+"
              link.download = title + this.getTodayDate() + ".docx";
            }
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
      }).finally(() => {
        this.loading = false;
      });
    },
    // 申请电子档 旧
    shenQdzdNew(type) {
      const ids = this.ids;
      // 查询数据
      const data = this.ywdwgdList.filter(item => ids.some(id => id === item.id))
      // 判断要导出的数据是否有：证书份数，回款金额，回款时间
      const yws = []
      let obj = ""
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (item.wgdh === '' || item.wgdh === null) {  // 证书
          obj += "(客户为： " + item.khname + " 的数据待完善 完工单号 ),"
        }else if (item.zjfs === '' || item.zjfs === null) {  // 证书
          obj += "(完工编号为：" +item.wgdh + " 客户为： " + item.khname + " 的数据待完善 证书份数 ),"
        }else if (item.hkje === '' || item.hkje === null) {
          obj += "(完工编号为：" +item.wgdh + " 客户为： " + item.khname + " 的数据待完善 回款金额 ),"
        }else {
          yws.push(item)
        }
      }
      if (obj.length > 200) {
        obj = obj.substring(0, 200) + "..."
      }
      if (yws.length === 0) {
        this.$message.error('请先完善 ' + obj)
        return
      }
      let title = ""
      if (obj !== '') {
        title = '请确认 ' + obj+' 这些数据待完善，未完善的数据则不能生成电子档'
      }else {
        if (type === 'dzd') {
          title = '请确认是否要生成电子档'
        }else if (type === 'zyzz') {
          title = '请确认是否要生成纸质文件'
        }else {
          title = '请确认是否要生成纸质文件和电子档'
        }
      }
      this.$modal.confirm(title).then(() => {
        this.loading = true;
        let idList = yws.map(obj => obj.id)
        let param = {
          ids: idList.toString(),
          type: type
        }
        genDzdNew(param, 'blob').then(res => {
          this.showDzdData = false
          if (res !== null) {
            const binaryData = [];
            binaryData.push(res);
            let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
            const link = document.createElement('a');
            link.href = url
            let title = ""
            if (param.type === 'dzd') {
              title = "只申请电子档证书+"
              link.download = title + this.getTodayDate() + ".xlsx";
            }else if (param.type === 'zyzz') {
              title = "未回款先递证书申请+"
              link.download = title + this.getTodayDate() + ".xlsx";
            }else {
              title = "未回款先递证书申请+"
              link.download = title + this.getTodayDate() + ".xlsx";
            }
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            // 批量修改状态
            let obj = {
              id: this.ids.toString(),
              sfsqdzd: '1'
            }
            batchUpdateZt(obj).then(res => {})
          }
        })
      }).finally(() => {
        this.loading = false;
      });
    },
    // 清洗完工单模板
    clearWgdMb() {

    },
    // 更新数据
    updateData() {
      if (this.form.sfgkhdzd !== undefined || this.form.sfkp !== undefined
        || this.form.sfsqdzd !== undefined || this.form.yyjkh !== undefined
        || this.form.zzdy !== undefined) {
        this.form.id = this.ids.toString()
        batchUpdateZt(this.form, this.ids).then(res => {
          if (res.code === 200 && res.data) {
            this.$message.success("更新成功！")
          }
        })
      }else {
       this.$message.error("请选择更新状态！")
      }
    },
    // 下载Excel
    downExcelData() {
      const ids = this.ids;
      const data = this.ywdwgdList.filter(item => ids.some(id => id === item.id))
      let obj = ""
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (obj.length > 200) {
          obj += "..."
          break
        }else {
          if (i === data.length-1) {
            obj += "编号为：" +item.bjdh + " 客户为： " + item.khname
          }else {
            obj += "编号为：" +item.bjdh + " 客户为： " + item.khname + ", "
          }
        }
      }
      this.$modal.confirm('请确认是否要下载 ' + obj+' 业务单的Excel').then(() => {
        this.loading = true;
        downLoadZip('/gd/ywdwgd/downExcel/ywd', "业务单_"+this.getFileDownName() , ids.toString())
      }).finally(() => {
        this.loading = false;
        this.getList();
      });
    },
    downExcelData_Wgd() {
      const ids = this.ids;
      const data = this.ywdwgdList.filter(item => ids.some(id => id === item.id))
      let obj = ""
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        if (obj.length > 200) {
          obj += "..."
          break
        }else {
          if (i === data.length-1) {
            obj += "编号为：" +item.bjdh + " 客户为： " + item.khname
          }else {
            obj += "编号为：" +item.bjdh + " 客户为： " + item.khname + ", "
          }
        }
      }
      this.$modal.confirm('请确认是否要下载 ' + obj+' 业务单的Excel').then(() => {
        this.loading = true;
        downLoadZip('/gd/ywdwgd/downExcel/wgd', "完工单_"+this.getFileDownName() , ids.toString())
      }).finally(() => {
        this.loading = false;
        this.getList();
      });
    },
    getFileDownName() {
      let date = new Date()
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      const hours = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
      const seconds = ('0' + date.getSeconds()).slice(-2);
      return `${year}${month}${day}${hours}${minutes}${seconds}`;
    },
    // 获取字典数据
    getDict() {
      this.getDicts("gd_sf").then(res => {
        this.sfList = res.data
      })
      // 是否回款
      this.getDicts("gd_sfhk").then(res => {
        this.hkList = res.data
      })
    },
    // 关闭数据
    cancelHandle() {
      this.$emit("cancelHandle")
    },
    getTodayDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      return `${year}${month}${day}`;
    }
  }
}
</script>

<style scoped>
.handle-content {
  width: 100%;
  height: 600px;
}
.el-radio {
  margin-right: 0px;
}
.el-checkbox {
  margin-right: 0px;
}
</style>
